package com.yonyou.wdt.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.dao.JobLogDao;
import com.yonyou.wdt.dao.WarehouseOrgDao;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.model.JobLogModel;
import com.yonyou.wdt.model.WarehouseOrgModel;
import com.yonyou.wdt.qimenmodel.qimencloud.api.DefaultQimenCloudClient;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.request.WdtStockOutDtlQueryRequest;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.request.WdtStockoutOrderQueryTradeRequest;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.response.WdtStockOutDtlQueryResponse;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.response.WdtStockoutOrderQueryTradeResponse;
import com.yonyou.wdt.service.CommonService;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class WdtQmSaleOutToYsSaleOrder extends BaseConfig {


    private static final Logger logger = LoggerFactory.getLogger(WdtQmSaleOutToYsSaleOrder.class);
    private final WdtConfigProperties configProperties;
    @Resource
    private YonsuiteService yonsuiteService;
    @Resource
    public JobLogDao jobLogDao;
    @Resource
    public WarehouseOrgDao warehouseOrgDao;
    @Resource
    public CommonService commonService;
    private static final String JOB_CLASS="maoEr007";
    @Autowired
    public WdtQmSaleOutToYsSaleOrder(WdtConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

    @XxlJob("WdtQmSaleOutToYsSaleOrder")
    public ReturnT<String> wdtQmSaleOutToYsSaleOrder(String params) throws Exception {
        String param = XxlJobHelper.getJobParam();
        Map<String, Object> map = new HashMap<>();
        if (param != null && !"".equals(param)) {
            if (param.contains("&")) {
                List<String> timeRange = Arrays.asList(param.split("&"));
                if (timeRange.size() == 2) {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                }else if (timeRange.size() == 3) {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                    map.put("shop_no", timeRange.get(2));
                } else {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                    map.put("shop_no", timeRange.get(2));
                    map.put("warehouse_no", timeRange.get(3));
                }
            } else {
                List<String> timeRange = Arrays.asList(param.split("\\|"));
                if (timeRange.size() == 2) {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                } else {
                    map.put("stockout_no", timeRange.get(0));
                }
            }
        } else {
            // 默认查询前一天的数据
            map.put("Start", DateUtils.getStartDate());
            map.put("End", DateUtils.getEndDate());
        }
        String dateStr = null;
        if (map.get("Start") != null && map.get("End") != null) {
            dateStr = map.get("Start").toString() + map.get("End").toString();
        }

        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(JOB_CLASS,dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        try {
            List<JSONObject> jsonObjectList = sendWdtByQm(map,dto);
            Integer successCount = 0;
            Integer failCount = 0;
            // jsonObjectList = new ArrayList<>();
            // 解析数据，组装YS请求参数
            if (!jsonObjectList.isEmpty()) {
                // 查询YS仓库档案列表
               // HashMap<String, String> ckData = getCkData(dto, yonsuiteService);
                for (int i = 0; i < jsonObjectList.size(); i++) {
                    JSONObject jsonObject = jsonObjectList.get(i);
                    //for (JSONObject jsonObject : responseList) {
                    Map<String, Object> ysSaveParam = assembleYsParams(jsonObject, dto,param);
                    if (ysSaveParam == null) {
                        failCount++;
                        continue;
                    }
                    JSONObject response = yonsuiteService.saleOrderSave(ysSaveParam, dto);
                    if (null != response && "200".equals(response.getStr("code"))) {
                        successCount++;
                        logger.info("旺店通销售出库汇总保存YS销售订单成功");
                        InsertLogger(JOB_CLASS,null, "1", "旺店通销售出库汇总保存YS销售订单" + response.getJSONObject("data").getStr("code") + "成功");
                    } else {
                        failCount++;
                        String string = response.getOrDefault("message", "").toString();
                        if (string.length()>=900){
                            string=string.substring(0,900);
                        }
                        logger.error("旺店通销售出库汇总保存YS销售订单失败：{}", string);
                        InsertLogger(JOB_CLASS,null, "0", "旺店通销售出库汇总保存YS销售订单失败" + string);
                    }
                    // 处理YS接口调用频率问题
                    // 调用YS接口保存数据
                    this.APICurrentLimiting(OpenApiURLEnum.SALES_ORDER_SAVE, 39);
                }
                logger.info("当前时间段：{} 需要同步到YS销售订单数据有：{}条", dateStr, jsonObjectList.size());
            }
            Thread.sleep(1000);
            InsertLogger(JOB_CLASS,null, "0", "当前时间段：" + dateStr + ",旺店通销售出库汇总一共" + jsonObjectList.size() + "条,保存YS销售订单成功:" + successCount + "条，失败:" + failCount + "条。");

        } catch (Exception e) {
            logger.error("Error occurred", e);
            logger.error("旺店通销售出库汇总同步YS销售订单失败，{}", e.getMessage());
            InsertLogger(JOB_CLASS,null, "0", "旺店通销售出库汇总同步YS销售订单失败" + e.getMessage());
            return ReturnT.FAIL;
        }
        logger.info("  --  旺店通销售出库汇总同步YS销售订单任务执行完成  --  ");
        return ReturnT.SUCCESS;
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 旺店通数据分组
     * @Date 10:21 2023/5/15
     * @Param
     **/
    private List<JSONObject> groupBy(List<JSONObject> responseList) {

        List<JSONObject> resultList = new ArrayList<>();
        try {
            Map<String, List<JSONObject>> createdDateMap = responseList.stream().collect(Collectors.groupingBy(json -> json.getStr("consign_time").substring(0, 10)));
            createdDateMap.forEach((payTime, createdValue) -> {
                Map<String,Map<String, List<JSONObject>>> collect = createdValue.stream().collect(Collectors.groupingBy(json -> json.getStr("shop_no"), Collectors.groupingBy(json -> json.getStr("warehouse_no"))));
                collect.forEach((shopNo, warehouseMap) -> {
                    warehouseMap.forEach((warehouseNo, warehouseItems) ->{
                        List<JSONObject> allItems = warehouseItems.stream().flatMap(element -> element.getJSONArray("details_list").stream()).map(o -> (JSONObject) o).collect(Collectors.toList());
                        //  Map<String, List<JSONObject>> detailsListBrandNoGroupMap = allItems.stream().collect(Collectors.groupingBy(json -> json.getStr("brand_no")));
                        //   detailsListBrandNoGroupMap.forEach((brandNo, brandNoMap) -> {
                        Map<String, List<JSONObject>> detailsListGoodsIdGroupMap = allItems.stream().collect(Collectors.groupingBy(json -> json.getStr("goods_no")));
                        JSONObject resultJson = new JSONObject();
                        List<JSONObject> itemsListResultList = detailsListGoodsIdGroupMap.entrySet().stream().map(entry -> {
                            List<JSONObject> items = entry.getValue();
                            BigDecimal qtyNew = items.stream().map(json -> json.getBigDecimal("num")).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal saleAmountNew = items.stream().map(json -> json.getBigDecimal("paid")).reduce(BigDecimal.ZERO, BigDecimal::add);

                            JSONObject theFirstItem = items.isEmpty() ? new JSONObject() : items.get(0);
                            theFirstItem.put("num", qtyNew);
                            theFirstItem.put("paid", saleAmountNew);
                            return theFirstItem;
                        }).collect(Collectors.toList());
                        resultJson.put("shop_no", shopNo);
                        resultJson.put("modified", payTime);
                        resultJson.put("consign_time", payTime);
                        resultJson.put("warehouse_no", warehouseNo);
                        resultJson.put("details_list", itemsListResultList);
                        resultList.add(resultJson);
                        //   });

                    });
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 组装YS请求数据
     * @Date 14:34 2023/5/17
     * @Param
     **/
    private Map<String, Object> assembleYsParams(JSONObject jsonObject, QueryDto dto,String param) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> body = new HashMap<>();
        // ==========主表============

        String shopNo = jsonObject.getStr("shop_no");
        String warehouseNo = jsonObject.getStr("warehouse_no");

        Object o = RedisUtils.get(dto.getTenantId() + ":cust:" + shopNo);
        if(o==null){
            // 保存同步错误日志，未找到对应客户档案信息
            logger.error("存在未同步YS系统客户数据：{}，请同步后重试", shopNo);
            InsertLogger(JOB_CLASS,null, "0", "存在未同步YS系统客户数据："+shopNo+"，请同步后重试");
            return null;
        }
        String orgId = JSONUtil.parseObj(o).getStr("createOrgCode");//管理组织
        //String orgId = "01";
        body.put("warehouse", warehouseNo); // 仓库id或编码


        body.put("salesOrgId", orgId);  // 销售组织，传id或者code
        body.put("transactionTypeId", "maoer01");  // 交易类型，传id或者code - 销售出库

	/*	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String vouchdate = format.format(jsonObject.getLong("bill_date"));*/
        body.put("vouchdate", jsonObject.getStr("modified")); // 单据日期
        body.put("agentId", shopNo);  // 客户，传id或者code
        //body.put("saleDepartmentId", shopNo);  // 销售部门，传id或者code
        // body.put("corpContact", "00000017");  // 销售业务员，传id或者code
        body.put("settlementOrgId", orgId);  // 开票组织，传id或者code
        body.put("orderPrices!currency", "CNY");  // 币种，传id或者code
        body.put("orderPrices!exchRate", 1);  // 汇率
        body.put("orderPrices!exchangeRateType", "01");  // 汇率类型，传id或者code
        body.put("orderPrices!natCurrency", "CNY");  // 本币，传id或者code
        body.put("orderPrices!taxInclusive", true);  // 单价含税
        body.put("invoiceAgentId", shopNo);  // 开票客户，传id或者code
        body.put("_status", "Insert");  // 操作标识
        body.put("memo", "旺店通接口同步");  // 备注
  /*      HashMap<String, Object> defHashMap = new HashMap<>();
        defHashMap.put("E_01", jsonObject.getStr("pay_time"));
        defHashMap.put("E_06", ckData.get(warehouseNo));
        body.put("orderDefineCharacter", defHashMap);  // 表头自定义项特征组*/

        JSONArray items = jsonObject.getJSONArray("details_list");
        BigDecimal payMoney = BigDecimal.ZERO;
        // ==========子表============
        ArrayList<String> goodsList = new ArrayList<>();
        goodsList.add("NB0008");
        goodsList.add("NB0007");
        goodsList.add("AM001N");
        goodsList.add("NB0006");
        goodsList.add("NB0005");
        goodsList.add("NB0004");
        goodsList.add("NB0001");
        goodsList.add("NB0003");
        goodsList.add("NB0002");
        JSONArray details = new JSONArray();
        for (Object element : items) {
            JSONObject item = (JSONObject) element;
            // 获取物料编码
            String product = item.getStr("goods_no");
            Optional<String> any = goodsList.stream().filter(obj -> obj.equals(product)).findAny();
            if (any.isPresent()){
                continue;
            }
            //  String suiteNo = item.getStr("suite_no");
            // 获取Redis中物料档案信息
			JSONObject redisPrJson = (JSONObject) RedisUtils.get(dto.getTenantId() + ":product:" + product);
			if (redisPrJson == null) {
				// 保存同步错误日志，未找到对应物料档案信息
				logger.error("存在未同步YS系统物料数据：{}，请同步后重试", product);
				InsertLogger(JOB_CLASS,null, "0", "存在未同步YS系统物料数据："+product+"，请同步后重试");
				return null;
			}
            HashMap<String, Object> saleOutDetail = new HashMap<>();
            //BigDecimal saleAmount = BigDecimal.ZERO;
            BigDecimal outTaxrate;
            BigDecimal unitPriceIncludingTax = BigDecimal.ZERO;
            BigDecimal taxAmount = BigDecimal.ZERO;
            BigDecimal noTaxSaleAmount = BigDecimal.ZERO;
            BigDecimal taxFreeUnitPrice = BigDecimal.ZERO;
            BigDecimal nums = item.getBigDecimal("num");

            BigDecimal saleAmount = item.getBigDecimal("paid");
            // String taxId = "VATR1";
            String taxId = "NL";
            if (saleAmount != null) {
                // 金额
                // saleAmount = item.getBigDecimal("sum_sale");
                // 税率
                outTaxrate = redisPrJson.containsKey("outTaxrate_name") ? redisPrJson.getBigDecimal("outTaxrate_name") : BigDecimal.ZERO;
                taxId=redisPrJson.getStr("productDetail_outTaxrate") != null ? redisPrJson.getStr("productDetail_outTaxrate") : "NL";
                // 含税单价
                unitPriceIncludingTax = saleAmount.divide(nums, 4, RoundingMode.HALF_UP);
                // 税额
                if (!"0".equals(outTaxrate.toString())) {
                    taxAmount = saleAmount.divide(outTaxrate.divide(new BigDecimal(100)).add(new BigDecimal(1)), 4, RoundingMode.HALF_UP).multiply(outTaxrate.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)).setScale(2, RoundingMode.HALF_UP);
                    // taxAmount = saleAmount.multiply(outTaxrate.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP));
                }
                // 无税金额
                noTaxSaleAmount = saleAmount.subtract(taxAmount);
                // 无税单价
                taxFreeUnitPrice = noTaxSaleAmount.divide(BigDecimal.valueOf(Double.parseDouble(String.valueOf(nums))), 4, RoundingMode.HALF_UP);
            }
            payMoney = payMoney.add(saleAmount);
            String unit=redisPrJson.getStr("unitCode");
            // String unit = "无";
            saleOutDetail.put("productId", product); // 物料id或编码
            saleOutDetail.put("oriSum", saleAmount);  // 含税金额 BigDecimal
            saleOutDetail.put("saleCost", saleAmount);  // 报价含税金额 BigDecimal
            saleOutDetail.put("oriTaxUnitPrice", unitPriceIncludingTax);  // 含税成交价 BigDecimal
            saleOutDetail.put("salePrice", unitPriceIncludingTax);  // 含税报价  BigDecimal
            saleOutDetail.put("orderDetailPrices!oriUnitPrice", taxFreeUnitPrice);  // 无税成交价 BigDecimal
            saleOutDetail.put("noTaxSalePrice", taxFreeUnitPrice);  // 无税报价 BigDecimal
            saleOutDetail.put("orderDetailPrices!natSum", saleAmount);  // 本币含税金额
            saleOutDetail.put("orderDetailPrices!natMoney", noTaxSaleAmount);  // 本币无税金额
            saleOutDetail.put("orderDetailPrices!natTax", taxAmount);  // 本币税额 BigDecimal
            saleOutDetail.put("orderDetailPrices!oriTax", taxAmount);  // 税额 BigDecimal
            saleOutDetail.put("orderDetailPrices!oriMoney", noTaxSaleAmount);  // 无税金额 BigDecimal
            saleOutDetail.put("orderDetailPrices!natTaxUnitPrice", unitPriceIncludingTax);  // 本币含税单价 BigDecimal
            saleOutDetail.put("orderDetailPrices!natUnitPrice", taxFreeUnitPrice);  // 本币无税单价
            saleOutDetail.put("masterUnitId", unit);  // 主计量单位，传id或者code
            saleOutDetail.put("invExchRate", 1);  // 销售换算率 BigDecimal
            saleOutDetail.put("unitExchangeTypePrice", 0);  // 浮动（销售）int
            saleOutDetail.put("iProductAuxUnitId", unit);  // 销售单位，传id或者code
            saleOutDetail.put("invPriceExchRate", 1);  // 计价换算率
            saleOutDetail.put("priceQty", nums);  // 计价数量 BigDecimal
            saleOutDetail.put("stockOrgId", "01");  // 库存组织id或库存组织code
            saleOutDetail.put("stockId", warehouseNo);  // 仓库
            saleOutDetail.put("iProductUnitId", unit);  // 计价单位，传id或者code
            saleOutDetail.put("orderProductType", "SALE");  // 商品售卖类型
            saleOutDetail.put("subQty", nums);  // 销售数量 BigDecimal
            saleOutDetail.put("consignTime", jsonObject.getStr("modified"));  // 计划发货日期,格式为:yyyy-MM-dd HH:mm:ss
            saleOutDetail.put("taxId", taxId);  // 税目税率，传id或者code
            saleOutDetail.put("qty", nums);  // 数量 BigDecimal
            saleOutDetail.put("settlementOrgId", orgId);  // 开票组织，传id或者code
            saleOutDetail.put("unitExchangeType", 0);  // 浮动（计价） int
            saleOutDetail.put("_status", "Insert");  // 操作标识
          /*  saleOutDetail.put("batchNo",  StringUtils.isBlank(item.getStr("batch"))?"202412":item.getStr("batch"));
            saleOutDetail.put("invaliddate", StringUtils.isBlank(item.getStr("expire_date"))?"2027-12-31":item.getStr("expire_date"));*/

            //saleOutDetail.put("isBatchManage", true);  // 是否批次管理, true:是、false:否、    示例: false
            //saleOutDetail.put("batchNo", "旺店通");  // 批次号
            //调用销售保存接口时，子表为PTO母件商品行需要加个字段 "virtualProductAttribute":16
            /*if (item.containsKey("isSuite") && item.getBool("isSuite")) {
                saleOutDetail.put("productId", product); // 物料id或编码
                saleOutDetail.put("virtualProductAttribute", "16");
            }*/
           /* if (StringUtils.isNotBlank(suiteNo)) {
                HashMap<String, Object> detailDefMap = new HashMap<>();
                detailDefMap.put("E_05", nums);
                detailDefMap.put("E_03", item.getStr("src_tids"));
                detailDefMap.put("E_02", item.getStr("suite_no"));
                saleOutDetail.put("orderDetailDefineCharacter", detailDefMap);
            }*/
            details.add(saleOutDetail);
        }
        if (details.isEmpty()){
            return null;
        }
        body.put("payMoney", payMoney);  // 合计含税金额
        body.put("totalMoney", payMoney);  // 总金额

        body.put("orderDetails", details);
        // 幂等
        if (param.contains("&")){
            body.put("resubmitCheckKey", UUID.randomUUID().toString().replace("-",""));
        }else {
            body.put("resubmitCheckKey", "test2025020801");
            ReSubmitUtil.resubmitCheckKey(body);
        }
        data.put("data", body);
        return data;
    }



    private List<JSONObject> sendWdtByQm(Map<String, Object> map,QueryDto dto) throws Exception {
        // 根据客户查询旺店通店铺配置信息
      /*  Object ordisObj = RedisUtils.get(dto.getTenantId() + ":2BCust");
        if (ordisObj==null){
            InsertLogger(JOB_CLASS,null, "0", "旺店通销售出库汇总查询失败，未找到2B客户");
        }
        List<JSONObject> shoplist = JSONUtil.toList(JSONUtil.toJsonStr(ordisObj), JSONObject.class);
        List<String> shopNos = shoplist.stream().map(obj ->obj.getStr("code")).collect(Collectors.toList());*/
        // 根据客户查询旺店通店铺配置信息
        //自定义档案列表查询
        HashMap<String, String> custData = YsQueryUtil.getFhdpDef(dto,yonsuiteService);
        ArrayList<String> collect = new ArrayList<>();
        for (String s : custData.keySet()) {
            collect.add(custData.get(s));
        }
        List<String> shopNos=new ArrayList<>();
        shopNos.add("NJ004");
        shopNos.add("ND001");
        shopNos.add("NT005");
        shopNos.add("Z0001");
        shopNos.add("NX002");
        shopNos.addAll(collect);
        List<JSONObject> resList = new ArrayList<>();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(configProperties.getQmServerUrl(), configProperties.getQmAppKey(), configProperties.getQmAppSecret(), "json");
        Integer realityPageNo = 0;
        map.put("page_no", realityPageNo.toString());
        map.put("page_size", "100");
        // map.put("shop_no", "20240514-5");
        //map.put("warehouse_no", "1");
        //map.put("status", 95);
        boolean hasNext = true;
        //总页数
        Integer totalPage = 0;
        //总条数
        Integer total_count = 0;
        String consign_time = null;
        try {
            while (hasNext) {
                map.put("page_no", realityPageNo.toString());
                WdtStockoutOrderQueryTradeRequest req = this.setModel(map, configProperties.getQmTargetAppKey(), configProperties.getSid());
                WdtStockoutOrderQueryTradeResponse res = null;
                try {
                    res = client.execute(req);
                } catch (com.yonyou.wdt.qimenmodel.taobao.api.ApiException e) {
                    throw new RuntimeException(e);
                }
                JSONObject saleOutJson = JSONUtil.parseObj(res.getBody()).getJSONObject("response");
                if ("0".equals(saleOutJson.getStr("errorcode"))) {
                    //判断分页
                    if (realityPageNo == 0) {
                        total_count = saleOutJson.getInt("total_count", 0);
                        totalPage = total_count % 100 == 0 ? total_count / 100 : total_count / 100 + 1;
                    }
                    //每页订单列表
                    JSONArray orderArray = saleOutJson.getJSONArray("stockout_list");
                    if (orderArray.size() > 0) {
                        //resList.addAll(JSONUtil.toList(orderArray,JSONObject.class));

                        List<JSONObject> list = JSONUtil.toList(orderArray, JSONObject.class);
                        list = list.stream().filter(o -> "95".equals(o.getStr("status")) || "110".equals(o.getStr("status"))  || "105".equals(o.getStr("status"))).collect(Collectors.toList());
                        for (JSONObject entries : list) {
                            Boolean flag=false;
                            for (String shopNo : shopNos) {
                                if (shopNo.equals(entries.getStr("shop_no"))){
                                    flag=true;
                                    break;
                                }
                            }
                            if (!flag){
                                resList.add(entries);
                            }
                        }
                     //   resList.addAll(list);
                        resList = groupBy(resList);
                    }
                    //判断分页
                    if (realityPageNo == 0) {
                        total_count = saleOutJson.getInt("total_count", 0);
                        totalPage = total_count % 100 == 0 ? total_count / 100 : total_count / 100 + 1;
                    }
                    this.APICurrentLimiting("wdt.stockout.order.query.trade",59);
                    if (totalPage > realityPageNo + 1) {
                        realityPageNo += 1;
                    } else {
                        hasNext = false;
                    }
                } else {
                    InsertLogger(JOB_CLASS,null, "0", "旺店通销售出库接口查询失败" + saleOutJson.getStr("sub_message"));
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("Error occurred", e);
            logger.error("查询旺店通退货入库单失败：【{}】", e.getMessage());
        }
        return resList;
    }


    public static void main(String[] args) {
        ArrayList<Object> objects = new ArrayList<>();
        ArrayList<Object> newobjects = new ArrayList<>();
        objects.add(1);
        objects.add(2);
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add(3);
        objects1.add(4);
        for (Object o : objects1) {
            for (Object object : objects) {
                if (o!=object){
                    newobjects.add(o);
                }
                break;
            }
        }
        System.out.println(newobjects);
    }

    public WdtStockoutOrderQueryTradeRequest setModel(Map param, String targetAppKey, String sid) {
        WdtStockoutOrderQueryTradeRequest req = new WdtStockoutOrderQueryTradeRequest();
        //旺店通的奇门appkey
        req.setTargetAppKey(targetAppKey);
        //旺店通erp的卖家账号
        req.setSid(sid);
        String startTime = MapUtil.getStr(param, "Start");
        if (StringUtils.isNotBlank(startTime)) {
            req.setStartTime(startTime);
        }
        String endTime = MapUtil.getStr(param, "End");
        if (StringUtils.isNotBlank(endTime)) {
            req.setEndTime(endTime);
        }
        Long status = MapUtil.getLong(param, "status");
        if (status != null) {
            req.setStatus(status);
        }
        String srcOrderNo = MapUtil.getStr(param, "src_order_no");
        if (StringUtils.isNotBlank(srcOrderNo)) {
            req.setSrcOrderNo(srcOrderNo);
        }
        String srcTid = MapUtil.getStr(param, "src_tid");
        if (StringUtils.isNotBlank(srcTid)) {
            req.setSrcTid(srcTid);
        }
        String stockoutNo = MapUtil.getStr(param, "stockout_no");
        if (StringUtils.isNotBlank(stockoutNo)) {
            req.setStockoutNo(stockoutNo);
        }
        if (param.containsKey("page_no")) {
            req.setPageNo(MapUtil.getLong(param, "page_no"));
        }
        if (param.containsKey("page_size")) {
            req.setPageSize(MapUtil.getLong(param, "page_size"));
        }
        Integer isByModified = MapUtil.getInt(param, "is_by_modified");
        if (isByModified != null) {
            req.setIsByModified(isByModified);
        }
        String shop_no = MapUtil.getStr(param, "shop_no");
        if (StringUtils.isNotBlank(shop_no)) {
            req.setShopNo(shop_no);
        }
        if (param.containsKey("shop_nos")) {
            req.setShopNos(MapUtil.getStr(param, "shop_nos"));
        }
        String warehouseNo = MapUtil.getStr(param, "warehouse_no");
        if (StringUtils.isNotBlank(warehouseNo)) {
            req.setWarehouseNo(warehouseNo);
        }
        Integer isNoPosition = MapUtil.getInt(param, "is_no_position");
        if (isNoPosition != null) {
            req.setIsNoPosition(isNoPosition);
        }
        return req;
    }
}
